<template>
  <div class="pcbox bg_style border_style  " :id="`printMe${canvasItem.id}`" :ref="canvasItem.id">
    <one-template preview :templateBean="templateBean" :reportDataBean="reportDataBean"></one-template>
    <preview-tow-table :templateBean="templateBean" :reportDataBean="reportDataBean"></preview-tow-table>
    <template>
      <YsRow>
        <div class="preview-imgs border_style" :id="`three${this.teplModal.file_id}`">
          <p class="preview-title text_01">检测部位及缺陷位置实物图：</p>
          <div v-for="(item,index) in imgsBody" :class="{'mark':item.values[0].is_mark===1,'on_marked':item.values[0].is_mark!=1}" class="sign">
            <div class=" img-box" v-if="item.values[0].is_mark===1">
              <div v-for="(it, index) in item.fileFlawInfos" :key="index" class="rectangleList" :style="{left:`${it.label_left_x}px`,top:`${it.label_left_y}px`}">
                <p class="titleFlaw">{{it.flaw_type_name}}</p>
                <div class="shape" :style="{width:`${it.width}px`,height:`${it.height}px`}"> </div>
              </div>
            </div>
            <img class="preview-bg" :src="item.values[0].value">
          </div>
        </div>
      </YsRow>
    </template>
    <preview-four-form :templateBean="templateBean" :reportDataBean="reportDataBean"></preview-four-form>
  </div>
</template>
<script>

import { mapActions } from "vuex";
import oneTemplate from "./components/oneTemplate.vue";
import previewTowTable from "./components/previewTowTable.vue";
import previewThreeImgs from "./components/previewThreeImgs.vue";
import previewFourForm from "./components/previewFourForm.vue";
import html2canvas from "html2canvas";
import JsPDF from 'jspdf';
export default {
  name: 'canvasTempList',
  components: {
    oneTemplate,
    previewTowTable,
    previewThreeImgs,
    previewFourForm
  },
  props: {
    canvasItem: {
      type: Object,
      default: () => {
        return {}
      }
    },
  },
  data() {
    return {
      templateBean: {},
      reportDataBean: {},
      changeBeans: {},
      imgsBody: [],
      teplModal: {
        template_id: "",
        file_id: ""
      }
    }
  },

  mounted() {
    this.teplModal.template_id = this.canvasItem.template_id
    this.teplModal.file_id = this.canvasItem.id
    this.getParmasData()
  },
  methods: {
    ...mapActions(['getDetectImgDetail', 'getTemplateAllFieldAPI', "getviewFileReportDataAIP", "getFileReportFieldsAPI"]),
    //获取数据
    getImgDetail() {
      this.getDetectImgDetail({ file_id: this.teplModal.file_id }).then(async res => {
        let { data, msg, scode, status } = res;
        if (status === 'ok') {
          this.imgsBody[0].fileFlawInfos = await this.setParticle(data.fileFlawInfos)
        }
      })
    },
    //设置文件地址
    setParticle(data) {
      let newdata = data.map(v => {
        return { ...v, width: v.label_right_x - v.label_left_x, height: v.label_right_y - v.label_left_y }
      })
      return newdata
    },
    //获取数据
    async getParmasData(obj) {
      this.templateBean = await this.getFielBeanList()
      this.reportDataBean = await this.getFielBodyList()
      //拿到数据就转成base64，再进行一个页面的渲染
      if (this.reportDataBean && this.reportDataBean.table_field_data3) {
        this.reportDataBean.table_field_data3.map(async (v, index) => {
          let data = await this.loadImageAsync(v.values[0].value)
          v.values[0].value = data.img_path
          if (document.querySelectorAll(`#three${this.teplModal.file_id} .sign .preview-bg`)[index]) {
            document.querySelectorAll(`#three${this.teplModal.file_id} .sign `)[index].style.width = `${data.img_width}px`
            document.querySelectorAll(`#three${this.teplModal.file_id} .sign `)[index].style.height = `${data.img_height}px`
          }
        })
        this.imgsBody = this.reportDataBean.table_field_data3.map((v, index) => { return { ...v, fileFlawInfos: [] } })
        this.getImgDetail()
      }
      return this.reportDataBean
    },
    // 将图片转换为Base64
    async loadImageAsync(path) {
      let _this = this
      return await new Promise(function (resolve, reject) {
        const image = new Image()
        image.src = `${window.GlobalConfig.serviceProxy.BaseUrl}${path}` + '?timestamp=' + new Date().getTime()
        image.setAttribute('crossOrigin', 'Anonymous')
        image.onload = () => {
          let base64 = _this.image2Base64(image);
          resolve({ img_path: base64, img_width: image.width, img_height: image.height });
        };

      });
    },
    // 获取图片Base64编码
    image2Base64(img) {
      var canvas = document.createElement("canvas");
      canvas.width = img.width;
      canvas.height = img.height;
      var ctx = canvas.getContext("2d");
      ctx.drawImage(img, 0, 0, img.width, img.height);
      var dataURL = canvas.toDataURL("image/png");
      return dataURL;
    },
    // 获取字段列表
    async getFielBeanList() {
      return await new Promise((resolve) => {
        this.getFileReportFieldsAPI(this.teplModal).then(res => {
          let { data, msg, scode, status } = res;
          if (status === "ok") {
            resolve(data)
          } else {
            resolve({})
          }
        })
      })
    },
    //获取body数据
    async getFielBodyList() {
      return await new Promise((resolve) => {
        this.getviewFileReportDataAIP(this.teplModal).then(res => {
          let { data, msg, scode, status } = res;
          if (status === "ok") {
            resolve(data.reportDataBean)
          } else {
            resolve({})
          }
        })
      })
    },
    //导出报告
    onExport(flag, row, idnex) {
      const clientWidth = this.$refs[this.canvasItem.id].offsetWidth;
      const clientHeight = this.$refs[this.canvasItem.id].offsetHeight;
      const kh = [clientWidth, clientHeight];
      html2canvas(this.$refs[this.canvasItem.id], { useCORS: true, logging: true }).then((canvas) => {
        var pageData = canvas.toDataURL('image/jpeg', 1.0);
        if (flag) {
          var contentWidth = canvas.width;
          var contentHeight = canvas.height;
          var pageHeight = contentWidth / 592.28 * 841.89;
          var leftHeight = contentHeight;
          var position = 0;
          var imgWidth = 595.28;
          var imgHeight = 595.28 / contentWidth * contentHeight;
          var pdf = new JsPDF('', 'pt', 'a4');
          if (leftHeight < pageHeight) {
            pdf.addImage(pageData, 'JPEG', 0, 0, imgWidth, imgHeight);
          } else {    // 分页
            while (leftHeight > 0) {
              pdf.addImage(pageData, 'JPEG', 0, position, imgWidth, imgHeight);
              leftHeight -= pageHeight;
              position -= 841.89;
              //避免添加空白页
              if (leftHeight > 0) {
                pdf.addPage();
              }
            }
          }
          //可动态生成
          pdf.save('X射线探伤检测报告');
        } else {
          this.downloadPNG(pageData, kh);
        }
      });
    },
    //下载
    downloadPNG(imgUrl, kh) {
      this.getUrlBase64(imgUrl, kh).then((base64) => {
        const link = document.createElement('a');
        link.href = base64;
        link.download = `X射线探伤检测报告.png`;
        link.click();
      });
    },
    //设置
    getUrlBase64(url, kh) {
      return new Promise((resolve) => {
        let canvas = document.createElement('canvas');
        const ctx = canvas.getContext('2d');
        const img = new Image();
        img.crossOrigin = 'Anonymous'; // 允许跨域
        img.src = url;
        img.onload = () => {
          canvas.height = kh[1];
          canvas.width = kh[0];
          ctx.drawImage(img, 0, 0, kh[0], kh[1]);
          const dataURL = canvas.toDataURL('image/png');
          canvas = null;
          resolve(dataURL);
        };
      });
    }
  }
}
</script>
<style scoped lang='less'>
.pcbox {
  border: 1px solid rgba(207, 215, 229, 0.6);
  border-radius: 4px;
  // height: calc(100% - 102px);
  padding: 40px 68px;
  .line-box {
    margin-top: 80px;
    border: 1px solid rgba(207, 215, 229, 0.6);
    padding: 18px;
  }
}

.preview-imgs {
  // height: 500px;
  margin-top: 80px;
  padding-bottom: 50px;
  border: 1px solid #ccc;
  overflow: auto;
  .sign {
    margin-bottom: 50px;
    overflow: auto;
    margin: 0 auto 80px;
  }
  .mark {
    position: relative;
  }
  .on_marked {
    img {
      margin: 0 auto;
    }
  }
  .preview-title {
    font-size: 16px;
    font-family: PingFang SC;
    font-weight: 400;
    line-height: 22px;
    color: #405580;
    margin: 24px 0 0 18px;
  }
  .preview-bg {
    display: block;
  }
  .img-box {
    border: 1px solid transparent;

    position: absolute;
    height: 100%;
    left: 0;
    right: 0;
    top: 0;
    bottom: 0;
    z-index: 999;
    .dlcvno {
      position: absolute;
      top: 20px;
      right: 20px;
      font-size: 32px;

      span {
        font-size: 22px;
        margin-top: -4px;
      }

      // font-weight: bold   ;
    }

    .rectangleList {
      position: absolute;
      margin-left: -8px;
      .titleFlaw {
        margin-top: -20px;
        color: #d53939;
      }
    }

    .shape {
      width: 10px;
      height: 10px;
      border: 1px solid #d53939;
      // background: #d5393941;
    }
  }
}
</style>